package by.epam.trenings.vkphotorest.auth;

import by.epam.trenings.vkphotorest.utils.context.ContextHolder;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;

public class VkOauth {

	private static final String KEY_TOKEN = "token";
	private static final String USER_ID = "user_id";
	private static final String VK_SHARED_PREFS = "vk_oauth_token_USER_ID";

	public static final String AUTORIZATION_URL = "http://oauth.vk.com/authorize?client_id=3249778&redirect_uri=http://oauth.vk.com/blank.html&scope=friends,photos,offline&display=touch&response_type=token";

	private static final String REDIRECT = "http://oauth.vk.com/blank.html";

	public static void saveCredentials(String token, String userId) {
		Editor editor = ContextHolder.getInstance().getContext()
				.getSharedPreferences(VK_SHARED_PREFS, Context.MODE_PRIVATE)
				.edit();
		editor.putString(KEY_TOKEN, token);
		editor.putString(USER_ID, userId);
		editor.commit();
	}

	public static String getUserId() {
		Context ctx = ContextHolder.getInstance().getContext();
		SharedPreferences savedSession = ctx.getSharedPreferences(
				VK_SHARED_PREFS, Context.MODE_PRIVATE);
		return savedSession.getString(USER_ID, null);
	}

	public static String sign(String url) {

		Context ctx = ContextHolder.getInstance().getContext();

		SharedPreferences savedSession = ctx.getSharedPreferences(
				VK_SHARED_PREFS, Context.MODE_PRIVATE);
		if (url.indexOf("?") > 0) {
			return url + "&access_token="
					+ savedSession.getString(KEY_TOKEN, null);
		} else if (url.equals("")) {
			return savedSession.getString(KEY_TOKEN, null);
		} else {
			return url + "?access_token="
					+ savedSession.getString(KEY_TOKEN, null);
		}
	}

	public static boolean isRedirect(String url) {
		return url.startsWith(REDIRECT);
	}

	public static boolean proceedRedirectURL(String url, final Runnable success) {
		if (isRedirect(url)) {
			Uri parseUrl = Uri.parse(url);
			final String token = parseUrl.getFragment();
			if (token == null) {
				return false;
			}
			final String tok = token.split("=")[1];

			final String userId = parseUrl.toString().split("user_id=")[1];

			VkOauth.saveCredentials(tok.split("&")[0], userId);
			if (success != null) {
				success.run();
			}
			return true;
		}
		return false;
	}
}
